from collections import defaultdict

# 定义训练器类
class TrainerA:
    def __init__(self, cfg):
        self.cfg = cfg
        print(f"Trainer A created with config: {cfg}")

class TrainerB:
    def __init__(self, cfg):
        self.cfg = cfg
        print(f"Trainer B created with config: {cfg}")

# 构建 TRAINERS 模块
TRAINERS = defaultdict(lambda: None)
TRAINERS['trainer_a'] = TrainerA
TRAINERS['trainer_b'] = TrainerB

# 构建方法
def build(config):
    trainer_type = config['type']
    trainer_class = TRAINERS[trainer_type]
    if trainer_class is not None:
        return trainer_class(config['cfg'])
    else:
        raise ValueError(f"Unknown trainer type: {trainer_type}")


# 使用示例
cfg = {
    'train': {
        'type': 'trainer_a',
        'other_config': 'some other configuration'
    }
}

# 构建训练器
trainer = build(dict(type=cfg['train']['type'], cfg=cfg))